<template>
  <div class="calendar-container">
    <!-- 左侧边栏 -->
    <div class="calendar-sidebar">
      <div class="sidebar-header">
        <button class="add-event-btn" @click="showAddEventDialog = true">
          + 新建事件
        </button>
      </div>

      <div class="sidebar-content">
        <!-- 迷你日历 -->
        <div class="mini-calendar">
          <div class="mini-calendar-header">
            <button class="nav-btn" @click="calendarStore.goToPrevious">‹</button>
            <span class="current-month">{{ currentMonthYear }}</span>
            <button class="nav-btn" @click="calendarStore.goToNext">›</button>
          </div>
          <div class="mini-calendar-grid">
            <div v-for="day in weekDays" :key="day" class="weekday-label">
              {{ day }}
            </div>
            <div
              v-for="(date, index) in calendarStore.currentMonthDays"
              :key="index"
              class="mini-day"
              :class="{
                today: calendarStore.isToday(date),
                'other-month': !calendarStore.isCurrentMonth(date),
                'has-events': calendarStore.getEventsForDate(date).length > 0
              }"
              @click="selectedDate = date"
            >
              {{ date.getDate() }}
            </div>
          </div>
        </div>

        <!-- 日历列表 -->
        <div class="calendars-section">
          <div class="section-title">我的日历</div>
          <div
            v-for="cal in calendarStore.calendars"
            :key="cal.id"
            class="calendar-item"
          >
            <input
              type="checkbox"
              :checked="cal.enabled"
              @change="toggleCalendar(cal.id)"
            />
            <span class="calendar-color" :style="{ background: cal.color }"></span>
            <span class="calendar-name">{{ cal.name }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="calendar-main">
      <!-- 工具栏 -->
      <div class="toolbar">
        <div class="toolbar-left">
          <button class="today-btn" @click="calendarStore.goToToday">今天</button>
          <button class="nav-btn" @click="calendarStore.goToPrevious">‹</button>
          <button class="nav-btn" @click="calendarStore.goToNext">›</button>
          <h2 class="current-title">{{ currentMonthYear }}</h2>
        </div>

        <div class="toolbar-right">
          <div class="view-switcher">
            <button
              class="view-btn"
              :class="{ active: calendarStore.viewMode === 'day' }"
              @click="calendarStore.setViewMode('day')"
            >
              日
            </button>
            <button
              class="view-btn"
              :class="{ active: calendarStore.viewMode === 'week' }"
              @click="calendarStore.setViewMode('week')"
            >
              周
            </button>
            <button
              class="view-btn"
              :class="{ active: calendarStore.viewMode === 'month' }"
              @click="calendarStore.setViewMode('month')"
            >
              月
            </button>
          </div>
        </div>
      </div>

      <!-- 月视图 -->
      <div class="calendar-view" v-if="calendarStore.viewMode === 'month'">
        <!-- 星期标题 -->
        <div class="weekdays-header">
          <div v-for="day in weekDaysLong" :key="day" class="weekday-col">
            {{ day }}
          </div>
        </div>

        <!-- 日期网格 -->
        <div class="days-grid">
          <div
            v-for="(date, index) in calendarStore.currentMonthDays"
            :key="index"
            class="day-cell"
            :class="{
              today: calendarStore.isToday(date),
              'other-month': !calendarStore.isCurrentMonth(date),
              selected: isSameDay(date, selectedDate)
            }"
            @click="handleDayClick(date)"
            @dblclick="handleDayDoubleClick(date)"
          >
            <div class="day-number">{{ date.getDate() }}</div>
            <div class="day-events">
              <div
                v-for="event in calendarStore.getEventsForDate(date).slice(0, 3)"
                :key="event.id"
                class="event-item"
                :style="{ background: event.color }"
                @click.stop="handleEventClick(event)"
              >
                <span class="event-time" v-if="!event.allDay">
                  {{ formatEventTime(event.startDate) }}
                </span>
                <span class="event-title">{{ event.title }}</span>
              </div>
              <div
                v-if="calendarStore.getEventsForDate(date).length > 3"
                class="more-events"
              >
                +{{ calendarStore.getEventsForDate(date).length - 3 }} 更多
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 周视图和日视图占位 -->
      <div v-else class="view-placeholder">
        <p>{{ calendarStore.viewMode === 'week' ? '周视图' : '日视图' }}开发中...</p>
      </div>
    </div>

    <!-- 添加事件对话框 -->
    <div v-if="showAddEventDialog" class="dialog-overlay" @click="closeAddDialog">
      <div class="dialog event-dialog" @click.stop>
        <div class="dialog-header">
          <h3>{{ editingEvent ? '编辑事件' : '新建事件' }}</h3>
          <button class="close-btn" @click="closeAddDialog">×</button>
        </div>
        <div class="dialog-body">
          <div class="form-group-inline">
            <label class="form-label-inline">标题</label>
            <input
              type="text"
              class="form-input"
              v-model="newEvent.title"
              placeholder="添加标题"
            />
          </div>

          <div class="form-group-inline">
            <label class="form-label-inline">开始</label>
            <div class="datetime-row">
              <DatePicker v-model="newEvent.startDate" placeholder="选择日期" />
              <TimePicker
                v-if="!newEvent.allDay"
                v-model="newEvent.startTime"
                placeholder="选择时间"
              />
            </div>
          </div>

          <div class="form-group-inline">
            <label class="form-label-inline">结束</label>
            <div class="datetime-row">
              <DatePicker v-model="newEvent.endDate" placeholder="选择日期" />
              <TimePicker
                v-if="!newEvent.allDay"
                v-model="newEvent.endTime"
                placeholder="选择时间"
              />
            </div>
          </div>

          <div class="form-group-inline">
            <label class="form-label-inline">选项</label>
            <div class="options-row">
              <label class="checkbox-label">
                <input type="checkbox" v-model="newEvent.allDay" />
                全天
              </label>
              <div class="select-wrapper">
                <Select
                  v-model="newEvent.calendar"
                  :options="calendarOptions"
                  placeholder="选择日历"
                />
              </div>
            </div>
          </div>

          <div class="form-group-inline">
            <label class="form-label-inline">颜色</label>
            <div class="color-picker">
              <div
                v-for="color in eventColors"
                :key="color"
                class="color-option"
                :class="{ active: newEvent.color === color }"
                :style="{ background: color }"
                @click="newEvent.color = color"
              ></div>
            </div>
          </div>

          <div class="form-group-inline">
            <label class="form-label-inline">备注</label>
            <textarea
              class="form-textarea"
              v-model="newEvent.notes"
              placeholder="添加备注..."
              rows="2"
            ></textarea>
          </div>
        </div>
        <div class="dialog-footer">
          <button
            v-if="editingEvent"
            class="dialog-btn danger"
            @click="handleDeleteEvent"
          >
            删除
          </button>
          <button class="dialog-btn cancel" @click="closeAddDialog">取消</button>
          <button class="dialog-btn primary" @click="handleSaveEvent">
            {{ editingEvent ? '更新' : '添加' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useCalendarStore, type CalendarEvent } from '@/stores/calendar.ts'
import DatePicker from '../../ui/DatePicker.vue'
import TimePicker from '../../ui/TimePicker.vue'
import Select from '../../ui/Select.vue'

interface SelectOption {
  value: string
  label: string
  color?: string
}

const calendarStore = useCalendarStore()

const selectedDate = ref(new Date())
const showAddEventDialog = ref(false)
const editingEvent = ref<CalendarEvent | null>(null)

const weekDays = ['一', '二', '三', '四', '五', '六', '日']
const weekDaysLong = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']

// 日历选项
const calendarOptions = computed<SelectOption[]>(() => {
  return calendarStore.calendars.map(cal => ({
    value: cal.name,
    label: cal.name,
    color: cal.color
  }))
})

const eventColors = [
  '#007AFF', // 蓝色
  '#34C759', // 绿色
  '#FF9500', // 橙色
  '#FF3B30', // 红色
  '#AF52DE', // 紫色
  '#FF2D55', // 粉色
  '#5856D6', // 靛蓝
  '#00C7BE', // 青色
]

const newEvent = ref({
  title: '',
  startDate: null as Date | null,
  startTime: '09:00',
  endDate: null as Date | null,
  endTime: '10:00',
  allDay: false,
  color: '#007AFF',
  notes: '',
  location: '',
  calendar: '工作'
})

// 当前月年
const currentMonthYear = computed(() => {
  return calendarStore.currentDate.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long'
  })
})

// 格式化事件时间
function formatEventTime(date: Date): string {
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 判断是否是同一天
function isSameDay(date1: Date, date2: Date | null): boolean {
  if (!date2) return false
  return (
    date1.getFullYear() === date2.getFullYear() &&
    date1.getMonth() === date2.getMonth() &&
    date1.getDate() === date2.getDate()
  )
}

// 点击日期
function handleDayClick(date: Date) {
  selectedDate.value = date
}

// 双击日期（快速添加事件）
function handleDayDoubleClick(date: Date) {
  selectedDate.value = date
  openAddDialog(date)
}

// 点击事件
function handleEventClick(event: CalendarEvent) {
  editingEvent.value = event
  newEvent.value = {
    title: event.title,
    startDateStr: event.startDate.toISOString().split('T')[0],
    startTimeStr: event.startDate.toTimeString().slice(0, 5),
    endDateStr: event.endDate.toISOString().split('T')[0],
    endTimeStr: event.endDate.toTimeString().slice(0, 5),
    allDay: event.allDay,
    color: event.color,
    notes: event.notes || '',
    location: event.location || '',
    calendar: event.calendar
  }
  showAddEventDialog.value = true
}

// 打开添加对话框
function openAddDialog(date: Date) {
  const dateStr = date.toISOString().split('T')[0]
  newEvent.value = {
    title: '',
    startDateStr: dateStr,
    startTimeStr: '09:00',
    endDateStr: dateStr,
    endTimeStr: '10:00',
    allDay: false,
    color: '#007AFF',
    notes: '',
    location: '',
    calendar: '工作'
  }
  editingEvent.value = null
  showAddEventDialog.value = true
}

// 关闭对话框
function closeAddDialog() {
  showAddEventDialog.value = false
  editingEvent.value = null
  // 重置表单
  newEvent.value = {
    title: '',
    startDate: null,
    startTime: '09:00',
    endDate: null,
    endTime: '10:00',
    allDay: false,
    color: '#007AFF',
    notes: '',
    location: '',
    calendar: '工作'
  }
}

// 保存事件
function handleSaveEvent() {
  if (!newEvent.value.title.trim()) {
    alert('请输入事件标题')
    return
  }

  if (!newEvent.value.startDate || !newEvent.value.endDate) {
    alert('请选择开始和结束日期')
    return
  }

  const startDate = new Date(newEvent.value.startDate)
  const endDate = new Date(newEvent.value.endDate)

  if (!newEvent.value.allDay) {
    const [startHour, startMinute] = newEvent.value.startTime.split(':')
    const [endHour, endMinute] = newEvent.value.endTime.split(':')
    startDate.setHours(parseInt(startHour), parseInt(startMinute))
    endDate.setHours(parseInt(endHour), parseInt(endMinute))
  }

  const eventData = {
    title: newEvent.value.title,
    startDate,
    endDate,
    allDay: newEvent.value.allDay,
    color: newEvent.value.color,
    notes: newEvent.value.notes,
    location: newEvent.value.location,
    calendar: newEvent.value.calendar
  }

  if (editingEvent.value) {
    calendarStore.updateEvent(editingEvent.value.id, eventData)
  } else {
    calendarStore.addEvent(eventData)
  }

  closeAddDialog()
}

// 删除事件
function handleDeleteEvent() {
  if (editingEvent.value && confirm('确定要删除此事件吗？')) {
    calendarStore.deleteEvent(editingEvent.value.id)
    closeAddDialog()
  }
}

// 切换日历显示
function toggleCalendar(calendarId: string) {
  const calendar = calendarStore.calendars.find(c => c.id === calendarId)
  if (calendar) {
    calendar.enabled = !calendar.enabled
    calendarStore.saveToStorage()
  }
}
</script>

<style scoped>
.calendar-container {
  display: flex;
  height: 100%;
  background: #f5f5f7;
  overflow: hidden;
}

/* 左侧边栏 */
.calendar-sidebar {
  width: 240px;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(20px);
  border-right: 1px solid rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 48px 16px 16px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.add-event-btn {
  width: 100%;
  padding: 10px;
  background: #007aff;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: background 0.2s;
}

.add-event-btn:hover {
  background: #0051d5;
}

.sidebar-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

/* 迷你日历 */
.mini-calendar {
  margin-bottom: 24px;
}

.mini-calendar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.current-month {
  font-size: 13px;
  font-weight: 600;
  color: #1d1d1f;
}

.mini-calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 4px;
}

.weekday-label {
  font-size: 10px;
  color: #86868b;
  text-align: center;
  padding: 4px 0;
}

.mini-day {
  aspect-ratio: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 11px;
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.2s;
}

.mini-day:hover {
  background: rgba(0, 0, 0, 0.05);
}

.mini-day.today {
  background: #007aff;
  color: white;
  font-weight: 600;
}

.mini-day.other-month {
  color: #c7c7cc;
}

.mini-day.has-events {
  font-weight: 600;
}

/* 日历列表 */
.calendars-section {
  margin-top: 16px;
}

.section-title {
  font-size: 11px;
  font-weight: 600;
  color: #86868b;
  text-transform: uppercase;
  margin-bottom: 8px;
  letter-spacing: 0.5px;
}

.calendar-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 0;
  font-size: 13px;
}

.calendar-color {
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

.calendar-name {
  flex: 1;
  color: #1d1d1f;
}

/* 主内容区 */
.calendar-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
}

/* 工具栏 */
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 48px 20px 12px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.today-btn {
  padding: 6px 16px;
  border: 1px solid rgba(0, 0, 0, 0.2);
  border-radius: 6px;
  background: white;
  font-size: 13px;
  color: #1d1d1f;
  cursor: pointer;
  transition: all 0.2s;
}

.today-btn:hover {
  background: rgba(0, 0, 0, 0.05);
}

.nav-btn {
  width: 32px;
  height: 32px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 6px;
  background: white;
  font-size: 20px;
  color: #1d1d1f;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-btn:hover {
  background: rgba(0, 0, 0, 0.05);
}

.current-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #1d1d1f;
}

.view-switcher {
  display: flex;
  gap: 4px;
  background: rgba(0, 0, 0, 0.05);
  border-radius: 8px;
  padding: 2px;
}

.view-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 6px;
  background: transparent;
  font-size: 13px;
  color: #1d1d1f;
  cursor: pointer;
  transition: all 0.2s;
}

.view-btn.active {
  background: white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

/* 日历视图 */
.calendar-view {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.weekdays-header {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
  padding: 12px 20px;
  background: #fafafa;
}

.weekday-col {
  text-align: center;
  font-size: 12px;
  font-weight: 600;
  color: #86868b;
}

.days-grid {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  grid-template-rows: repeat(6, 1fr);
  gap: 1px;
  background: rgba(0, 0, 0, 0.05);
  padding: 0 20px 20px;
}

.day-cell {
  background: white;
  padding: 8px;
  cursor: pointer;
  transition: all 0.2s;
  overflow-y: auto;
  min-height: 80px;
}

.day-cell:hover {
  background: rgba(0, 122, 255, 0.05);
}

.day-cell.today {
  background: rgba(0, 122, 255, 0.1);
}

.day-cell.selected {
  outline: 2px solid #007aff;
}

.day-cell.other-month .day-number {
  color: #c7c7cc;
}

.day-number {
  font-size: 13px;
  font-weight: 500;
  color: #1d1d1f;
  margin-bottom: 4px;
}

.day-cell.today .day-number {
  display: inline-block;
  background: #007aff;
  color: white;
  width: 24px;
  height: 24px;
  line-height: 24px;
  text-align: center;
  border-radius: 50%;
}

.day-events {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.event-item {
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 11px;
  color: white;
  cursor: pointer;
  transition: opacity 0.2s;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.event-item:hover {
  opacity: 0.8;
}

.event-time {
  margin-right: 4px;
  font-weight: 600;
}

.more-events {
  font-size: 10px;
  color: #86868b;
  margin-top: 2px;
  cursor: pointer;
}

/* 占位视图 */
.view-placeholder {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #86868b;
  font-size: 18px;
}

/* 对话框 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 500;
}

.dialog {
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  width: 600px;
  max-width: 90vw;
  max-height: 85vh;
  overflow: visible;
  display: flex;
  flex-direction: column;
}

.dialog-header {
  padding: 16px 20px 12px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-radius: 12px 12px 0 0;
  background: white;
}

.dialog-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1d1d1f;
}

.close-btn {
  width: 28px;
  height: 28px;
  border: none;
  background: transparent;
  font-size: 24px;
  color: #86868b;
  cursor: pointer;
  border-radius: 50%;
  transition: background 0.2s;
}

.close-btn:hover {
  background: rgba(0, 0, 0, 0.05);
}

.dialog-body {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 16px 20px;
  min-height: 0;
  background: white;
}

/* 滚动条样式 */
.dialog-body::-webkit-scrollbar {
  width: 8px;
}

.dialog-body::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}

.dialog-body::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.2);
  border-radius: 4px;
}

.dialog-body::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 0, 0, 0.3);
}

.form-group-inline {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  margin-bottom: 12px;
  overflow: visible;
}

.form-group-inline:last-child {
  margin-bottom: 0;
}

.form-label-inline {
  flex-shrink: 0;
  width: 60px;
  padding-top: 10px;
  font-size: 13px;
  font-weight: 500;
  color: #1d1d1f;
  text-align: right;
}

.form-group-inline > :not(.form-label-inline) {
  flex: 1;
  min-width: 0;
  overflow: visible;
}

.form-input {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid rgba(0, 0, 0, 0.2);
  border-radius: 6px;
  font-size: 14px;
  font-family: inherit;
}

.form-input:focus {
  outline: none;
  border-color: #007aff;
}

.form-textarea {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid rgba(0, 0, 0, 0.2);
  border-radius: 6px;
  font-size: 14px;
  font-family: inherit;
  resize: vertical;
  min-height: 50px;
  max-height: 100px;
}

.form-textarea:focus {
  outline: none;
  border-color: #007aff;
}

.datetime-row {
  display: flex;
  gap: 8px;
  overflow: visible;
}

.datetime-row .form-input {
  flex: 1;
}

.options-row {
  display: flex;
  gap: 12px;
  align-items: center;
  overflow: visible;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  cursor: pointer;
  white-space: nowrap;
}

.checkbox-label input[type="checkbox"] {
  width: 16px;
  height: 16px;
  cursor: pointer;
}

.select-wrapper {
  flex: 1;
  min-width: 0;
}

.color-picker {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
  align-items: center;
}

.color-option {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.2s;
  border: 2px solid transparent;
}

.color-option:hover {
  transform: scale(1.15);
}

.color-option.active {
  border-color: #1d1d1f;
  box-shadow: 0 0 0 2px white, 0 0 0 4px #1d1d1f;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding: 12px 20px 16px;
  border-top: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 0 0 12px 12px;
  background: white;
}

.dialog-btn {
  padding: 8px 20px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.dialog-btn.cancel {
  background: transparent;
  border: 1px solid rgba(0, 0, 0, 0.2);
  color: #1d1d1f;
}

.dialog-btn.cancel:hover {
  background: rgba(0, 0, 0, 0.05);
}

.dialog-btn.primary {
  background: #007aff;
  border: none;
  color: white;
}

.dialog-btn.primary:hover {
  background: #0051d5;
}

.dialog-btn.danger {
  background: #ff3b30;
  border: none;
  color: white;
  margin-right: auto;
}

.dialog-btn.danger:hover {
  background: #cc0000;
}

/* 响应式 */
@media (max-width: 768px) {
  .calendar-sidebar {
    width: 60px;
  }

  .sidebar-header,
  .calendars-section,
  .mini-calendar {
    display: none;
  }

  .days-grid {
    grid-template-rows: repeat(6, minmax(60px, 1fr));
  }
}
</style>

